// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import Sprite from "./custom/Sprite"
import Group from './custom/Group';
import { getTime } from './support';

export default class Entity extends Sprite {

    frame_index 
    animation_speed
    direction : cc.Vec2 = null

    obstacle_sprites : Group

    constructor(groups) {
        super(groups)
        this.frame_index = 0
		this.animation_speed = 0.03
		this.direction = cc.v2(0, 0)
    }

    move(speed) {

        if(this.direction.mag() != 0) {
            this.direction = this.direction.normalize()
        }

        this.hitbox.x += this.direction.x * speed
        this.collision('horizontal')
        this.hitbox.y += this.direction.y * speed
        this.collision('vertical')
        this.rect.center = this.hitbox.center
    }

    collision(direction) {

        if(direction == 'horizontal') {
            for(let sprite of this.obstacle_sprites.getSprites()) {
                if(cc.Intersection.rectRect(sprite.hitbox, this.hitbox)) {
                    if(this.direction.x > 0) { // moving right
                        // 左下角
                        let x = sprite.hitbox.xMin - this.hitbox.width - 0.5
                        let y = this.hitbox.y
                        this.hitbox = cc.rect(x, y, this.hitbox.width, this.hitbox.height)
                    }
                    if(this.direction.x < 0) { // moving left
                        let x = sprite.hitbox.xMax + 0.5
                        let y = this.hitbox.y
                        this.hitbox = cc.rect(x, y, this.hitbox.width, this.hitbox.height)
                    }
                }
                
            }
        }

        if(direction == 'vertical') {
            for(let sprite of this.obstacle_sprites.getSprites()) {
                if(cc.Intersection.rectRect(sprite.hitbox, this.hitbox)) {
                    if(this.direction.y < 0) { // moving down
                        let x = this.hitbox.x 
                        let y = sprite.hitbox.yMax + 0.5
                        this.hitbox = cc.rect(x, y, this.hitbox.width, this.hitbox.height)
                    }
                    if(this.direction.y > 0) { // moving up
                        let x = this.hitbox.x
                        let y = sprite.hitbox.yMin - this.hitbox.height - 0.5
                        this.hitbox = cc.rect(x, y, this.hitbox.width, this.hitbox.height)
                    }
                }
            }
        }


    }

    wave_value() {
        let value = Math.sin(getTime())
        if(value >= 0) {
            return 255
        } else {
            return 0
        }
    }

}


